package session

import (
	"context"
	"gf-demo/internal/consts"
	"gf-demo/internal/model/entity"
	"gf-demo/internal/service"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

type (
	sSession struct{}
)

func init() {
	service.RegisterSession(New())
}

func New() service.ISession {
	return &sSession{}
}

// SetUser sets user into the session.
func (s *sSession) SetUser(ctx context.Context, user *entity.SysUser) error {
	return service.BizCtx().Get(ctx).Session.Set(consts.UserSessionKey, user)
}

// GetUser retrieves and returns the user from session.
// It returns nil if the user did not sign in.
func (s *sSession) GetUser(ctx context.Context) *entity.SysUser {
	customCtx := service.BizCtx().Get(ctx)
	if customCtx != nil {
		if v := customCtx.Session.MustGet(consts.UserSessionKey); !v.IsNil() {
			var user *entity.SysUser
			_ = v.Struct(&user)
			return user
		}
	}
	return nil
}

// RemoveUser removes user rom session.
func (s *sSession) RemoveUser(ctx context.Context) error {
	customCtx := service.BizCtx().Get(ctx)
	if customCtx != nil {
		err := customCtx.Session.Remove(consts.UserSessionKey)
		if err != nil {
			return err
		}
		str, _ := service.Locale().T(ctx, `logout_success`)
		return gerror.NewCode(gcode.CodeOK, str)
	}
	str, _ := service.Locale().T(ctx, `session_not_exist`)
	return gerror.NewCode(gcode.CodeNotFound, str)
}
